package com.smartplatform.service.impl;

import com.smartplatform.cache.RoleCache;
import com.smartplatform.constants.ResultCode;
import com.smartplatform.exception.QueryException;
import com.smartplatform.mapper.SysMenuMapper;
import com.smartplatform.mapper.SysUserRoleMapper;
import com.smartplatform.pojo.MyBaseUser;
import com.smartplatform.pojo.SysMenu;
import com.smartplatform.service.SysMenuService;
import com.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 咕唧
 * @Date 2022/5/31 20:21
 * @Version 1.0
 */
@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {
    private SysMenuMapper sysMenuMapper;
    private SysUserRoleMapper sysUserRoleMapper;
    private RoleCache roleCache;

    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Autowired
    public void setSysUserRoleMapper(SysUserRoleMapper sysUserRoleMapper) {
        this.sysUserRoleMapper = sysUserRoleMapper;
    }

    @Autowired
    public void setSysMenuMapper(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    public List<SysMenu> findAll() {
        //获取用户信息
        MyBaseUser userInfo = SecurityUtils.getUserInfo(false);
        Assert.notNull(userInfo, () -> {
            throw new QueryException("用户未登录", ResultCode.USER_NOT_LOGIN);
        });

//        List<SysMenu> menuList = sysMenuMapper.selectAll();
//        List<SysMenu> collect = menuList.stream()
//                .filter(sysMenu -> 0 != sysMenu.getParentId() && "M".equals(sysMenu.getMenuType()))
//                .collect(Collectors.toList());


        //根据用户的id从缓存中获取到所有的角色id
        List<Long> roleIds = sysUserRoleMapper.selectRoleIdByUserId(userInfo.getUserId());

        //根据用户权限过滤有效菜单
        List<SysMenu> enableMenuList = new ArrayList<>();
        roleIds.forEach(roleId -> {
            //根据角色id获取角色,id获取菜单
            List<SysMenu> menuList = roleCache.get(roleIds.get(0)).getMenuList();
            //过滤菜单
            List<SysMenu> collect = menuList.stream()
                    .filter(sysMenu -> 0 != sysMenu.getParentId() && "M".equals(sysMenu.getMenuType()))
                    .collect(Collectors.toList());
            enableMenuList.addAll(collect);
        });

        return enableMenuList;
    }
}
